package com.zhuhjay.common.core.security.handler;

import cn.hutool.extra.servlet.ServletUtil;
import com.zhuhjay.common.base.enums.HttpCode;
import com.zhuhjay.common.base.model.vo.HttpResult;
import com.zhuhjay.common.security.context.AuthenticationExceptionContext;
import com.zhuhjay.common.web.util.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 访问权限认证失败处理器
 * @author ZhuHJay
 * @date 2023/4/24 14:53
 */
@Slf4j
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        // 判断访问失败的问题
        HttpCode code = AuthenticationExceptionContext.getCode();
        if (code != null) {
            log.warn("访问认证失败 -> uri: {}, ip: {}, reason: {}", request.getRequestURI(), ServletUtil.getClientIP(request), code.getDesc());
            // 认证失败
            ServletUtils.writeToJson(response, HttpResult.fail(code));
        } else {
            log.warn("HttpCode null -> uri: {}, ip: {}", request.getRequestURI(), ServletUtil.getClientIP(request));
            ServletUtils.writeToJson(response, HttpResult.fail(HttpCode.SERVER_ERROR));
        }
    }

}
